import echarts from 'echarts'
import $http from '../utils/http.js'
import { Notification } from 'atelement'
import $download from '../utils/download.js'
const riskwarningData = 'riskwarning/riskData'
const Derailsallunitnames = 'riskwarningDerails/allunitnames'

const riskwarningssort = 'riskwarning/sotr'
const riskwarningsfilters = 'riskwarning/filters'
const riskwarningchValue = 'riskwarning/changeSearchValue'
const riskwarningChange = 'riskwarning/paginationChange'
const riskwarningSubmitWaring = 'riskwarning/submitWaring'
const riskwarningyujing = 'riskwarning/yujing'
const riskwarningDerailInitil = 'riskwarningDerails/InitialValue'
const riskwarningDerailalarmlog = 'riskwarningDerails/alarmlog'
const riskwarningDeraildownload = 'riskwarningDerails/download'
const clear = 'riskwarning/clear'
export default{
  state: {
    riskData: [],
    nodesinfo: [],
    allunitnames: [],
    risk_sum: {},
    echarts: {
      type: ['新兴', '高危', '流行', '攻击类'],
      color: ['#ffd140', '#1f92ef', '#53cb7b'],
      data: [ { value: 0, name: '新兴' }, { value: 0, name: '高危' }, { value: 0, name: '流行' }, { value: 0, name: '攻击类' } ]
    },
    riskwarningSubmit: {
      pagination: {
        total: 0,
        current: 1, // 当前页码
        pageSize: 20 // 当前页显示的数据条数
      },
      search: {
        value: '' // 需要模糊搜索的值（搜索框）
      },
      sorter: {
        field: 'asubmit_time', // 排序的字段
        order: 'descend' // 升序还是降序
      },
      filters: {
        // 需要被过滤的字段
        arisk_event_level: [],
        arisk_event_type: [],
        aearly_warn: []
      },
      dict: {
        // 额外参数
      }
    }
  },
  actions: {
    // 风险事项获取表格数据
    [riskwarningData] ({ commit, state }) {
      $http.option('/api/riskwarning/getdata', state.riskwarningSubmit)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            commit(riskwarningData, data)
          } else if (status === 'fail') {
            Notification.warning(msg)
          }
        })
    },
    // Derailsallunitnames
    [Derailsallunitnames] ({ commit, state }) {
      $http.option('/api/Derailsall/unitnames')
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            commit(Derailsallunitnames, data)
          } else if (status === 'fail') {
            Notification.warning(msg)
          }
        })
    },
    // 风险详情通过id获取数据接口
    [riskwarningDerailInitil] ({ commit, dispatch }, { data, fun }) {
      $http.post('/api/riskwarning/Derails/getInitil', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            fun('detaildata', data.dataSource)
            fun('correlation', data.correlation)
            fun('TimeLineData', data.operate)
          } else if (status === 'fail') {
            Notification.error({
              title: '加载失败',
              message: msg
            })
          }
        })
    },
    // 告警日志riskwarningDerailalarmlog
    [riskwarningDerailalarmlog] ({ commit, dispatch }, { data, fun }) {
      $http.post('/api/riskwarning/Derails/larmlog', data)
        .then(({ status, msg, data } = {}) => {
          if (status === 'success') {
            fun('appendix', data['dataSource'])
          } else if (status === 'fail') {
            Notification.error({
              title: '加载失败',
              message: msg
            })
          }
        })
    },
    // 根据依据路径下载相对应的文件
    [riskwarningDeraildownload] ({ commit, dispatch }, { data }) {
      $download.post('/api/riskwarning/download', data)
    },
    // 风险事项筛选值
    [riskwarningsfilters] ({ commit, dispatch }, filters) {
      commit(riskwarningsfilters, filters)
      dispatch(riskwarningData)
    },
    // 风险详情排序值
    [riskwarningssort] ({ commit, dispatch }, { key, value }) {
      commit(riskwarningssort, { key, value })
      dispatch(riskwarningData)
    },
    // 风险管理改变搜索值
    [riskwarningchValue] ({ commit, dispatch }, value) {
      commit(riskwarningchValue, value)
      dispatch(riskwarningData)
    },
    // 风险管理改变页码值
    [riskwarningChange] ({ commit, dispatch }, value) {
      commit(riskwarningChange, value)
      dispatch(riskwarningData)
    },
    // 风险事项预警
    [riskwarningSubmitWaring] ({ dispatch }, { postData, fun, eventId }) {
      $http.post('/api/warning/issuedWarning', postData)
        .then(({ status, msg } = {}) => {
          if (status === 'success') {
            dispatch(riskwarningyujing, { data: postData, fun: fun, eventId })
          } else if (status === 'fail') {
            Notification.error({
              title: '预警失败',
              message: msg
            })
          }
        })
    },
    [riskwarningyujing] ({ dispatch }, { data, fun, eventId }) {
      $http.post('/api/riskwarning/yujing', data)
        .then(({ status, msg } = {}) => {
          if (status === 'success') {
            dispatch(riskwarningDerailInitil, { data: eventId, fun: fun })
            dispatch(riskwarningDerailalarmlog, { data: eventId, fun: fun })
            // fun('iscomit', 0)
            Notification.success({
              title: '预警成功',
              message: msg
            })
          } else if (status === 'fail') {
            Notification.error({
              title: '预警失败',
              message: msg
            })
          }
        })
    }
  },
  mutations: {
    [riskwarningData] (state, data) {
      state.riskData = data.dataSource
      // state.nodesinfo = data.nodesinfo
      // state.allunitnames = data.allunitnames
      // 对返回分数据进行分类并整理
      for (let x = 0; x < data.echarts.length; x++) {
        for (let i = 0; i < state.echarts['type'].length; i++) {
          if (data.echarts[x]['risk_event_type'] === state.echarts['type'][i]) {
            state.echarts['data'][i]['value'] = data.echarts[x]['count']
          }
        }
      }
      if (document.getElementById('warningtypemap')) {
        let m = document.getElementById('warningtypemap')
        let myChart = echarts.init(m)
        let option = {
          title: {
            text: '风险预警类型分布',
            x: 'left',
            left: 10,
            top: 15,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a}{b}: {c}'
          },
          legend: {
            orient: 'vertical',
            icon: 'circle',
            left: '230',
            top: '50',
            itemWidth: 7,
            itemHeight: 7,
            formatter: function (name) {
              for (let i = 0; i < state.echarts['data'].length; i++) {
                if (state.echarts['data'][i]['name'] === name) {
                  return name + ': ' + state.echarts['data'][i]['value']
                }
              }
            }
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: ['40%', '60%'], // 内圆和外圆
              center: ['30%', '60%'], // 位置
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  formatter: '{c}',
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  color: '#5c6781',
                  textStyle: {
                    fontSize: '16'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: state.echarts['data']
            }
          ],
          color: ['#ffd140', '#1f92ef', '#53cb7b', '#ff9933']
        }
        myChart.setOption(option)
      }
      if (document.getElementById('watningtypemapone')) {
        let m = document.getElementById('watningtypemapone')
        let myChart = echarts.init(m)
        let option = {
          title: {
            text: '风险预警下发状态分布',
            x: 'left',
            left: 10,
            top: 15,
            textStyle: {
              fontSize: 12
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a}{b}: {c}'
          },
          legend: {
            orient: 'vertical',
            icon: 'circle',
            left: '230',
            top: '50',
            itemWidth: 7,
            itemHeight: 7
            // formatter: function (name) {
            //   // 遍历json数组
            //   for (let key in data.echartsone) {
            //     if (key === name) {
            //       return name + ': ' + data.echartsone[key]
            //     }
            //   }
            // }
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: ['40%', '60%'], // 内圆和外圆
              center: ['30%', '60%'], // 位置
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  formatter: '{c}',
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  color: '#5c6781',
                  textStyle: {
                    fontSize: '16'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              // data: [ { value: data.echartsone['未预警'], name: '未预警' }, { value: data.echartsone['已预警'], name: '已预警' } ]
              data: [ { value: data.echartsone.nowaring, name: `未下发: ${data.echartsone.nowaring}` }, { value: data.echartsone.alwaring, name: `已下发: ${data.echartsone.alwaring}` } ]
            }
          ],
          color: ['RGB(255,201,51)', '#52CB7B']
        }
        myChart.setOption(option)
      }

      state.risk_sum = data.sumrisk
      let i = []
      let x = []
      let y = []
      data.timeecharts.forEach(function (val, index) {
        i.push(val.r_time)
        x.push(val.all_risk_cnt)
        y.push(val.analysis_risk_cnt)
      })
      if (document.getElementById('warningbigpolang')) {
        let m = document.getElementById('warningbigpolang')
        let myChart = echarts.init(m)
        let option = {
          xAxis: {
            type: 'category',
            data: i,
            boundaryGap: false,
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#1f92ef'
              }
            }
          },
          yAxis: {
            type: 'value',
            show: false
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'none',
              label: {
                backgroundColor: '#6a7985'
              }
            },
            textStyle: {
              color: '#fff',
              fontSize: 12,
              fontFamily: 'SimSun'
            }
          },
          series: [
            {
              name: '风险预警总数',
              type: 'line',
              smooth: true,
              areaStyle: {
                color: '#e8f4fd',
                opacity: 1
              },
              lineStyle: {
                width: 1,
                color: '#e8f4fd'
              },
              itemStyle: {
                color: '#e8f4fd'
              },
              symbol: 'none',
              data: x
            },
            {
              name: '已下发预警数',
              type: 'line',
              smooth: true,
              areaStyle: {
                color: '#1f92ef',
                opacity: 1
              },
              lineStyle: {
                width: 1,
                color: '#1f92ef'
              },
              itemStyle: {
                color: '#1f92ef'
              },
              symbol: 'none',
              data: y
            }
          ],
          grid: {
            top: 5,
            bottom: 1,
            left: 0,
            right: 0
          }
        }
        myChart.setOption(option)
      }
    },
    [Derailsallunitnames] (state, data) {
      state.nodesinfo = data.allunitnames
      state.allunitnames = data.allunitnamestree
    },
    // 风险事项筛选值
    [riskwarningsfilters] (state, filters) {
      if (filters.arisk_event_level !== undefined) {
        state.riskwarningSubmit.filters.arisk_event_level = filters.arisk_event_level
      }
      if (filters.aearly_warn !== undefined) {
        state.riskwarningSubmit.filters.aearly_warn = filters.aearly_warn
      }
      if (filters.arisk_event_type !== undefined) {
        state.riskwarningSubmit.filters.arisk_event_type = filters.arisk_event_type
      }
    },
    // 风险事项排序
    [riskwarningssort] (state, { key, value }) {
      state.riskwarningSubmit.sorter.field = key
      state.riskwarningSubmit.sorter.order = value
    },
    // 风险事项搜索
    [riskwarningchValue] (state, value) {
      if (value.type) {
        state.riskwarningSubmit.search.value = value.search
      } else {
        state.riskwarningSubmit.dict.userFlag = value.userFlag
      }
    },
    // 将前端的页码值和显示数给state
    [riskwarningChange] (state, value) {
      if (value.size) {
        state.riskwarningSubmit.pagination.pageSize = value.size
      }
      if (value.current) {
        state.riskwarningSubmit.pagination.current = value.current
      }
    },
    [clear] (state) {
      state.riskwarningSubmit = {
        pagination: {
          total: 0,
          current: 1, // 当前页码
          pageSize: 20 // 当前页显示的数据条数
        },
        search: {
          value: '' // 需要模糊搜索的值（搜索框）
        },
        sorter: {
          field: 'asubmit_time', // 排序的字段
          order: 'descend' // 升序还是降序
        },
        filters: {
          // 需要被过滤的字段
          arisk_event_level: [],
          arisk_event_type: [],
          aearly_warn: []
        },
        dict: {
          // 额外参数
        }
      }
    }
  }
}
